const { query, withTransaction } = require("../utils/db");
const { v4: uuidv4 } = require("uuid");

// 获取所有路由（树形结构）
exports.getAllRoutes = async () => {
  // 查询所有路由
  const routes = await query("SELECT * FROM t_routes ORDER BY FOrderNum");

  const routeMap = new Map();
  const rootRoutes = [];

  // 先建立映射，但不要提前加 children
  routes.forEach((route) => {
    routeMap.set(route.FId, { ...route }); // 拷贝一下，避免污染
  });

  // 构建树
  routes.forEach((route) => {
    const parentId = route.FParentId;
    if (parentId && routeMap.has(parentId)) {
      const parent = routeMap.get(parentId);
      if (!parent.children) parent.children = []; // 只有真正需要时再加
      parent.children.push(routeMap.get(route.FId));
    } else if (!parentId) {
      rootRoutes.push(routeMap.get(route.FId));
    }
  });

  return rootRoutes;
};

// 添加新路由
exports.addRoute = async (routeData) => {
  const FId = uuidv4();
  const {
    FParentId = null,
    FPath,
    FName,
    FComponent,
    FRedirect = null,
    FIcon = "Menu",
    FTitle,
    FIsLink = "",
    FIsHide = 0,
    FIsFull = 0,
    FIsAffix = 0,
    FIsKeepAlive = 1,
    FOrderNum = 0,
  } = routeData;

  await query(
    `INSERT INTO t_routes 
     (FId, FParentId, FPath, FName, FComponent, FRedirect, FIcon, FTitle, 
      FIsLink, FIsHide, FIsFull, FIsAffix, FIsKeepAlive, FOrderNum)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
    [
      FId,
      FParentId,
      FPath,
      FName,
      FComponent,
      FRedirect,
      FIcon,
      FTitle,
      FIsLink,
      FIsHide,
      FIsFull,
      FIsAffix,
      FIsKeepAlive,
      FOrderNum,
    ]
  );

  return { FId, ...routeData };
};

// 更新路由
exports.updateRoute = async (FId, routeData) => {
  const updates = [];
  const params = [];

  const fields = [
    "FParentId",
    "FPath",
    "FName",
    "FComponent",
    "FRedirect",
    "FIcon",
    "FTitle",
    "FIsLink",
    "FIsHide",
    "FIsFull",
    "FIsAffix",
    "FIsKeepAlive",
    "FOrderNum",
  ];

  fields.forEach((field) => {
    if (routeData[field] !== undefined) {
      updates.push(`${field} = ?`);
      params.push(routeData[field]);
    }
  });

  if (updates.length === 0) {
    throw { status: 400, message: "无更新内容" };
  }

  params.push(FId);

  const { affectedRows } = await query(
    `UPDATE t_routes SET ${updates.join(", ")} WHERE FId = ?`,
    params
  );

  if (affectedRows === 0) {
    throw { status: 404, message: "路由不存在" };
  }

  return true;
};

// 删除路由
exports.deleteRoute = async (FId) => {
  return withTransaction(async (conn) => {
    // 先检查是否有子路由
    const children = await query(
      "SELECT FId FROM t_routes WHERE FParentId = ?",
      [FId],
      conn
    );

    if (children.length > 0) {
      throw { status: 400, message: "请先删除子路由" };
    }

    // 删除路由
    const { affectedRows } = await query(
      "DELETE FROM t_routes WHERE FId = ?",
      [FId],
      conn
    );

    if (affectedRows === 0) {
      throw { status: 404, message: "路由不存在" };
    }

    // 删除相关的角色权限
    await query("DELETE FROM t_role_routes WHERE FRouteId = ?", [FId], conn);

    return true;
  });
};

// 获取角色拥有的路由
exports.getRoleRoutes = async (FRoleId) => {
  // 查询所有路由
  const allRoutes = await query(`SELECT FTitle, FId, FParentId FROM t_routes ORDER BY FOrderNum`);

  // 查询角色有权限的路由ID
  const roleRoutes = await query(
    `SELECT FRouteId FROM t_role_routes WHERE FRoleId = ?`,
    [FRoleId]
  );

  // 将有权限的路由ID转换为Set方便查找
  const permissionRouteIds = new Set(roleRoutes.map((item) => item.FRouteId));

  // 为所有路由添加权限标记
  const routesWithPermission = allRoutes.map((route) => ({
    ...route,
    FHasPermission: permissionRouteIds.has(route.FId),
  }));

  return routesWithPermission;
};

// 更新角色路由权限
exports.updateRoleRoutes = async (FRoleId, routeIds) => {
  console.log(routeIds);
  
  return withTransaction(async (conn) => {
    // 删除原有权限
    await query("DELETE FROM t_role_routes WHERE FRoleId = ?", [FRoleId], conn);

    // 添加新权限
    if (routeIds && routeIds.length > 0) {
      const values = routeIds.map((routeId) => [FRoleId, routeId]);
      await query(
        "INSERT INTO t_role_routes (FRoleId, FRouteId) VALUES ?",
        [values],
        conn
      );
    }

    return true;
  });
};

// 获取用户的路由权限（用于前端动态路由）
exports.getUserRoutes = async (FUserId) => {
  const routes = await query(
    `SELECT r.* FROM t_routes r
     JOIN t_role_routes rr ON r.FId = rr.FRouteId
     JOIN t_user_roles ur ON rr.FRoleId = ur.FRoleId
     WHERE ur.FUserId = ?
     ORDER BY r.FOrderNum`,
    [FUserId]
  );

  // 构建树形结构
  const routeMap = new Map();
  const rootRoutes = [];

  routes.forEach((route) => {
    route.children = [];
    routeMap.set(route.FId, route);
  });

  routes.forEach((route) => {
    if (route.FParentId && routeMap.has(route.FParentId)) {
      routeMap.get(route.FParentId).children.push(route);
    } else if (!route.FParentId) {
      rootRoutes.push(route);
    }
  });

  // 转换为前端需要的格式
  return rootRoutes.map((route) => ({
    path: route.FPath,
    name: route.FName,
    component: route.FComponent,
    redirect: route.FRedirect || undefined,
    meta: {
      icon: route.FIcon,
      title: route.FTitle,
      isLink: route.FIsLink || "",
      isHide: Boolean(route.FIsHide),
      isFull: Boolean(route.FIsFull),
      isAffix: Boolean(route.FIsAffix),
      isKeepAlive: Boolean(route.FIsKeepAlive),
    },
    children:
      route.children.length > 0
        ? route.children.map((child) => ({
            path: child.FPath,
            name: child.FName,
            component: child.FComponent,
            meta: {
              icon: child.FIcon,
              title: child.FTitle,
              isLink: child.FIsLink || "",
              isHide: Boolean(child.FIsHide),
              isFull: Boolean(child.FIsFull),
              isAffix: Boolean(child.FIsAffix),
              isKeepAlive: Boolean(child.FIsKeepAlive),
            },
          }))
        : undefined,
  }));
};
